﻿using Base.Infrastructure.Dto.Request.TestPaper;
using Base.Infrastructure.Dto.Response;
using Base.Infrastructure.EFCore.MySql;
using Base.Infrastructure.IOC;
using Base.Infrastructure.Tools;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Base.Service.Instance
{
    public class TestPaperService : BaseService, Base.Service.Interface.ITestPaperService
    {
        private readonly TestPaperIOC _testPaperIOC;
        public readonly TestPaperDetailIOC _testPaperDetailIOC;

        public TestPaperService(TestPaperIOC testPaperIOC, TestPaperDetailIOC testPaperDetailIOC, IConfiguration configuration)
        {
            _testPaperIOC = testPaperIOC;
            _testPaperDetailIOC = testPaperDetailIOC;
        }

        /// <summary>
        /// 添加试卷
        /// </summary>
        /// <param name="question"></param>
        /// <returns></returns>
        private bool AddTestPaper(TestPaper testPaper)
        {
            _testPaperIOC._testPaperService.Add(testPaper);
            return _testPaperIOC._testPaperService.SaveChanges() > 0;
        }

        /// <summary>
        /// 添加试卷详情
        /// </summary>
        /// <param name="question"></param>
        /// <returns></returns>
        private bool AddTestPaperDetail(TestPaperDetail testPaperDetail)
        {
            _testPaperDetailIOC._testPaperDetailService.Add(testPaperDetail);
            return _testPaperDetailIOC._testPaperDetailService.SaveChanges() > 0;
        }

        /// <summary>
        /// 
        /// 添加试卷和试卷详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult AddTestPaper(TestPaperRequestDto dto)
        {
            string tpid = Config.GUID();
            //添加试卷
            this.AddTestPaper(new TestPaper
            {
                Tpid= tpid,
                Tpname=dto.Tpname,
                Tpcids=null,
                TptotalScore=dto.TptotalScore,
                Tpqcount=dto.Tpqcount,
                TppassScore=dto.TppassScore,
                Tplv=dto.Tplv,
                Tplabels=dto.Tplabels,
                Tpaction=dto.Tpaction,
                Tpauthor=dto.Tpauthor,
                TpisBan=dto.TpisBan,
                TpisPublish=dto.TpisPublish,
                TpcreateTime= DateTime.Now.ToString()
            });

            //循环添加试卷详情
            for (int i = 0; i < dto.TPDQID?.Length; i++)
            {
                string tpdid = Config.GUID();
                this.AddTestPaperDetail(new TestPaperDetail
                {
                    Tpdid = tpdid,
                    Tpdtpid = tpid,
                    Tpdqid = dto.TPDQID[i],
                    Tpdscore = dto.TPDScore[i]
                });
            }

            return GetResult(1, "操作成功");
        }
    }
}
